package com.xinsoft.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinsoft.aop.ano.SysLog;
import com.xinsoft.common.BusinessType;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.MesProcessDTO;
import com.xinsoft.entity.dto.MesProcessParam;
import com.xinsoft.entity.dto.QuaCheckItemParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.CusDevTestPointVo;
import com.xinsoft.entity.vo.CusTestPointVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MesProcessController
 * @Description 工序配置控制层
 * @Author Li9527
 * @Date 2023-7-17 15:43:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/mes/process")
@Api(value = "MesProcessController", tags = {"工序配置控制层"})
public class MesProcessController {

    @Autowired
    private MesProcessService processService;

    @Autowired
    private QuaCheckItemService checkItemService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    MesProcessTestpointRefService refService;

    @Autowired
    CusTestPointService cusTestPointService;

    @Autowired
    CusDeviceService cusDeviceService;

    @Autowired
    SysUserService userService;

    @Autowired
    MesDocumentService documentService;

    @Resource
    SysFileHisService fileHisService;

    @Resource
    MesProcessCheckRefService checkRefService;

    @Resource
    MesProcessDeviceRefService deviceRefService;

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 工序配置-新增
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @SysLog(title = "工序配置-新增", businessType = BusinessType.INSERT)
    @ApiOperation("新增")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> add(@RequestBody MesProcessDTO mesProcessDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(mesProcessDTO);
        // 默认已审核
        mesProcessDTO.setAuditId(Const.ADMIN_UID);
        mesProcessDTO.setAuditStatus(Integer.valueOf(configService.getOne(new QueryWrapper<SysConfig>().eq("param_key", "MES_PROCESS_DEFAULT_AUDIT_STATUS")).getParamValue()));
        MesProcess oldProcess = processService.getOne(new QueryWrapper<MesProcess>().eq("process_name", mesProcessDTO.getProcessName()));
        if (oldProcess != null) {
            return Response.fail("该工序配置已存在,请不要重复添加");
        }
        processService.create(mesProcessDTO);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 更新
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @ApiOperation("更新")
    @SysLog(title = "工序配置-编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> edit(@RequestBody MesProcessDTO mesProcessDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(mesProcessDTO);
        // 默认已审核
        mesProcessDTO.setAuditId(Const.ADMIN_UID);
        mesProcessDTO.setAuditStatus(Integer.valueOf(configService.getOne(new QueryWrapper<SysConfig>().eq("param_key", "MES_PROCESS_DEFAULT_AUDIT_STATUS")).getParamValue()));
        MesProcess oldProcess = processService.getOne(new QueryWrapper<MesProcess>().eq("process_name", mesProcessDTO.getProcessName()));
        if (oldProcess != null && !oldProcess.getId().equals(mesProcessDTO.getId())) {
            return Response.fail("该工序配置已存在,请不要重复添加");
        }
        processService.edit(mesProcessDTO);
        return Response.succeed();
    }
    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 获取详情
     * @Date 2023/5/17 9:57
     * @params id
     **/
    @ApiOperation("获取详情")
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        MesProcess mesProcess = processService.getById(id);
        return Response.succeed(mesProcess);
    }


    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 获取详情
     * @Date 2023/5/17 9:57
     * @params id
     **/
    @ApiOperation("通过工序id及设备id获取双集合")
    @GetMapping("/getInfoByDeviceId")
    public Response<?> getInfoByDeviceId(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        List<MesProcessDeviceRef> deviceRefList = deviceRefService.list(new QueryWrapper<MesProcessDeviceRef>().eq("process_id",id));
        for (int k = 0; k < deviceRefList.size(); k++) {
            MesProcessDeviceRef deviceRef = deviceRefList.get(k);
            List<MesProcessCheckRef> checkList1 = checkRefService.list(new QueryWrapper<MesProcessCheckRef>().eq("process_device_id", deviceRef.getId()));
            if (checkList1.size() > 0) {
                for (int i = 0; i < checkList1.size(); i++) {
                    QuaCheckItem quaCheckItem = checkItemService.getById(checkList1.get(i).getCheckItemId());
                    if (quaCheckItem != null) {
                        checkList1.get(i).setCheckItemCode(quaCheckItem.getCheckItemCode());
                        checkList1.get(i).setCheckItemName(quaCheckItem.getCheckItemName());
                    }
                }
            }
            deviceRefList.get(k).setProcessCheckRefList(checkList1);
            // 侵入测点对象集合，因为mes项目service无法调用cus设备的service
            List<MesProcessTestpointRef> list = refService.list(new QueryWrapper<MesProcessTestpointRef>().eq("process_device_id", deviceRef.getId()));
            List<CusTestPointVo> pointList = new ArrayList<>();
            if (list.size() > 0) {
                // 注入对象
                for (int i = 0; i < list.size(); i++) {
                    CusDevTestPointVo cusDevTestPoint = cusTestPointService.getCusTestPoint(list.get(i).getTestPointId());
                    CusTestPointVo cusTestPoint = new CusTestPointVo();
                    BeanUtils.copyProperties(cusDevTestPoint,cusTestPoint);
                    pointList.add(cusTestPoint);
                }
            }
            deviceRefList.get(k).setCusTestPointVoList(pointList);
        }

        return Response.succeed(deviceRefList);
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 删除
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("删除")
    @SysLog(title = "工序配置-删除", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            MesProcess mesProcess = processService.getById(ids.get(i));
            if (mesProcess != null && mesProcess.getAuditStatus().equals(Const.AUDIT_STATUS_NORMAL)) {
                return Response.fail("存在已审核工序配置，不允许删除");
            }
        }
        processService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 批量审核
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("工序配置-批量审核")
    @SysLog(title = "工序配置-批量审核", businessType = BusinessType.UPDATE)
    @PostMapping("/auditBatch")
    public Response<?> auditBacth(@RequestBody List<Integer> ids) {
        Integer auditId = TokenUtil.getUser().getId();
        List<MesProcess> list = processService.list(new QueryWrapper<MesProcess>().in("id", ids));
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAuditStatus(Const.AUDIT_STATUS_NORMAL);
            list.get(i).setAuditId(auditId);
        }
        processService.updateBatchById(list);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 批量反审核
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("工序配置-批量反审核")
    @SysLog(title = "工序配置-批量反审核", businessType = BusinessType.UPDATE)
    @PostMapping("/unAuditBatch")
    public Response<?> unAuditBatch(@RequestBody List<Integer> ids) {
        List<MesProcess> list = processService.list(new QueryWrapper<MesProcess>().in("id", ids));
        Integer auditId = TokenUtil.getUser().getId();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAuditStatus(Const.AUDIT_STATUS_WAIT);
            list.get(i).setAuditId(auditId);
        }
        processService.updateBatchById(list);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 检验项目-分页
     * @Date 2023/5/18 10:51
     * @params param
     **/
    @PostMapping("/check/pageList")
    public Response<?> pageList(@Valid @RequestBody QuaCheckItemParam param) {
        return Response.succeed(checkItemService.findPageListByParam(param));
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 工序配置-分页
     * @Date 2023/5/18 10:51
     * @params param
     **/
    @PostMapping("/pageList")
    public Response<?> pageList(@Valid @RequestBody MesProcessParam param) {
        return Response.succeed(processService.findPageListByParam(param));
    }

}
